package detail

import (
	models "awesomeProject1/models/pojo"
	"awesomeProject1/pkg/e"
	"awesomeProject1/pkg/gintool"
	"github.com/simplechain-org/client/log"
	"time"
	"xorm.io/xorm"
)

func (s *service) GetTransDetailsList(startDate, endDate time.Time, pager *gintool.Pager) (list []*models.MyLoanDetails, total int64, code int) {
	sql := s.db.Table(models.MyLoanDetails{})
	sql = sql.Where("`date` >= ? and date <= ?", startDate, endDate)
	total, err := sql.Limit(pager.PageSize, pager.NumStart).FindAndCount(&list)
	if err != nil {
		log.Error("数据库获取数据错误：", "err", err.Error())
		return nil, total, e.ErrorDbGetFail
	}
	return list, total, e.Ok
}

func (s *service) GetOrgMappingList(pager *gintool.Pager) (list []*models.LoanOrg, total int64, code int) {
	sql := s.db.Table(models.LoanOrg{})
	total, err := sql.Limit(pager.PageSize, pager.NumStart).FindAndCount(&list)
	if err != nil {
		log.Error("数据库获取数据错误：", "err", err.Error())
		return nil, total, e.ErrorDbGetFail
	}
	return list, total, e.Ok
}

func (s *service) AddOrgMappingList(orgMappingList []*models.LoanOrg) (affectedCount int64, err error) {
	affectedCount, err = s.db.Table(models.LoanOrg{}).Insert(orgMappingList)
	return
}

// GetSendDetailsList 获取本行已经发送的详情上传数据
func (s *service) GetSendDetailsList(engine *xorm.Engine, startDate, endDate time.Time) (list []models.UploadDetailsRecord, total int64, code int) {
	session := &xorm.Session{}
	if !startDate.IsZero() {
		session = engine.Where("date >= ?", startDate)
	}
	if !endDate.IsZero() {
		session.Where("date <= ?", endDate)
	}
	total, err := session.FindAndCount(&list)
	if err != nil {
		log.Error("数据库获取数据错误：", "err", err.Error())
		return nil, total, e.ErrorDbGetFail
	}
	return list, total, e.Ok
}

//GetFirstLoanDetailsByReceiptIdHash 通过借据号哈希查询到此笔借据的放款信息
func (s *service) GetFirstLoanDetailsByReceiptIdHash(receiptIdHash string) (firstLoanList []models.FirstLoan, count int64, err error) {
	count, err = s.db.Where("receipt_hash=?", receiptIdHash).FindAndCount(&firstLoanList)
	return
}
